<template>
  <div class="customer-service-container">
    <!-- 返回按钮 -->
    <button class="back-button" @click="goBack">
      <span class="back-icon">←</span>
      <span class="back-text">返回</span>
    </button>

    <!-- 聊天区域 -->
    <div class="chat-container">
      <div class="chat-header">
        <h2>在线客服</h2>
        <span class="status" :class="{ 'online': isConnected }">
          {{ isConnected ? '在线' : '离线' }}
        </span>
      </div>

      <!-- 消息列表 -->
      <div class="message-list" ref="messageList">
        <div v-for="(msg, index) in messages" :key="index" 
             :class="['message', msg.sender === username ? 'sent' : 'received']">
          <div class="message-content">
            <div class="message-header">
              <span class="sender">{{ msg.sender === username ? '我' : msg.sender }}</span>
              <span class="time">{{ msg.time }}</span>
            </div>
            <div class="text">{{ msg.content }}</div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="input-area">
        <input
          v-model="inputMessage"
          type="text"
          placeholder="请输入消息..."
          @keyup.enter="handleSendMessage"
        />
        <button @click="handleSendMessage">发送</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { initWebSocket, sendMessage, closeWebSocket, getConnectionState, getHistoryMessages } from '@/axios/customer'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const username = ref(route.params.username)
const messages = ref([])
const inputMessage = ref('')
const messageList = ref(null)
const isConnected = ref(false)

// 检查用户登录状态
const checkUserLogin = () => {
  if (!userStore.userInfo?.username) {
    ElMessage.error('请先登录')
    router.push('/login')
    return false
  }
  return true
}

// 时间格式化函数
const formatTime = (date) => {
  if (!(date instanceof Date)) date = new Date(date)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  })
}

// 加载历史消息
const loadHistoryMessages = async () => {
  try {
    const response = await getHistoryMessages(username.value, 'admin')
    if (response && Array.isArray(response)) {
      messages.value = response.map(msg => {
        const msgTime = msg.createTime ? new Date(msg.createTime) : new Date()
        return {
          type: 'MESSAGE',
          content: msg.content,
          sender: msg.sender,
          toName: msg.receiver,
          time: formatTime(msgTime),
          timestamp: msgTime.getTime()
        }
      }).sort((a, b) => a.timestamp - b.timestamp)
      // 滚动到底部
      nextTick(() => {
        if (messageList.value) {
          messageList.value.scrollTop = messageList.value.scrollHeight
        }
      })
    }
  } catch (error) {
    console.error('加载历史消息失败:', error)
    ElMessage.error('加载历史消息失败')
  }
}

// 处理接收到的消息
const handleMessage = (message) => {
  if (message.type === 'MESSAGE') {
    const messageTime = message.createTime ? new Date(message.createTime) : new Date()
    messages.value.push({
      ...message,
      time: formatTime(messageTime),
      timestamp: messageTime.getTime()
    })
    // 滚动到底部
    nextTick(() => {
      if (messageList.value) {
        messageList.value.scrollTop = messageList.value.scrollHeight
      }
    })
  }
}

// 发送消息
const handleSendMessage = () => {
  // 如果输入框为空，则不发送消息
  if (!inputMessage.value.trim()) {
    return
  }
  const message = {
    type: 'MESSAGE',
    content: inputMessage.value,
    toName: 'admin',
    sender: username.value
    // 不加时间，等后端回包
  }
  if (sendMessage(message)) {
    inputMessage.value = ''
    // 不直接push，等WebSocket回包
  } else {
    ElMessage.error('连接已断开，请刷新页面重试')
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 检查连接状态
const checkConnection = () => {
  isConnected.value = getConnectionState() === 'OPEN'
}

onMounted(async () => {
  // 先加载历史消息
  await loadHistoryMessages()
  // 然后初始化WebSocket连接
  initWebSocket(handleMessage)
  // 定期检查连接状态
  const interval = setInterval(checkConnection, 5000)
  onUnmounted(() => {
    clearInterval(interval)
  })
})

onUnmounted(() => {
  closeWebSocket()
})
</script>

<style scoped>
.customer-service-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px;
  min-height: calc(100vh - 60px);
  position: relative;
  background-color: #f5f7fa;
}

.back-button {
  position: absolute;
  top: 20px;
  left: 30px;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 24px;
  background: white;
  border: none;
  border-radius: 30px;
  font-size: 16px;
  color: #2c3e50;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  z-index: 10;
}

.back-button:hover {
  transform: translateX(-4px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
  background: #f8f9fa;
}

.back-icon {
  font-size: 20px;
  font-weight: 500;
}

.back-text {
  font-weight: 500;
}

.chat-container {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
  margin-top: 60px;
  overflow: hidden;
}

.chat-header {
  padding: 24px;
  border-bottom: 1px solid #eee;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
}

.chat-header h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 22px;
  font-weight: 600;
}

.status {
  padding: 6px 16px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  background: #f56c6c;
  color: white;
  box-shadow: 0 2px 8px rgba(245, 108, 108, 0.2);
}

.status.online {
  background: #67c23a;
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.2);
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 24px;
  background: #f8f9fa;
}

.message {
  display: flex;
  flex-direction: column;
  max-width: 70%;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.message.sent {
  align-self: flex-end;
}

.message.received {
  align-self: flex-start;
}

.message-content {
  padding: 14px 18px;
  border-radius: 16px;
  position: relative;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.message.sent .message-content {
  background: #4CAF50;
  color: white;
  border-bottom-right-radius: 4px;
}

.message.received .message-content {
  background: white;
  color: #333;
  border-bottom-left-radius: 4px;
}

.message-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
  font-size: 12px;
}

.sender {
  color: #666;
}

.message.sent .sender {
  color: rgba(255, 255, 255, 0.9);
}

.time {
  margin-left: 8px;
  color: #999;
}

.message.sent .time {
  color: rgba(255, 255, 255, 0.8);
}

.text {
  word-break: break-word;
  line-height: 1.6;
  font-size: 15px;
}

.input-area {
  padding: 24px;
  border-top: 1px solid #eee;
  background: white;
  display: flex;
  gap: 12px;
}

.input-area input {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #e0e0e0;
  border-radius: 24px;
  font-size: 15px;
  transition: all 0.3s ease;
}

.input-area input:focus {
  outline: none;
  border-color: #4CAF50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.1);
}

.input-area button {
  padding: 12px 24px;
  background: #4CAF50;
  color: white;
  border: none;
  border-radius: 24px;
  font-size: 15px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.input-area button:hover {
  background: #43a047;
  transform: translateY(-1px);
}

.input-area button:active {
  transform: translateY(0);
}

@media (max-width: 768px) {
  .customer-service-container {
    padding: 15px;
  }

  .chat-container {
    height: calc(100vh - 90px);
    margin-top: 40px;
    border-radius: 12px;
  }

  .message {
    max-width: 85%;
  }

  .input-area {
    padding: 16px;
  }

  .input-area input {
    padding: 10px 14px;
  }

  .input-area button {
    padding: 10px 20px;
  }
}
</style> 